//
//  TodaySignTableview.m
//  BOSS-SOOC
//
//  Created by houshijia on 16/9/2.
//  Copyright © 2016年 Gcx. All rights reserved.
//

#import "TodaySignTableview.h"
#import "SC_TextFeild.h"
#import "TodaySignCell.h"
@interface TodaySignTableview()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,TodaySignCellDelegate,StuSignDelegate,UIImagePickerControllerDelegate>
{
    NSInteger _photoNum;
    NSData * _pubImageData;
    AFHTTPRequestOperationManager *_headerManager;

}
@property (nonatomic,strong) NSMutableArray<SignModel*> *orders;




@end

@implementation TodaySignTableview

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)init{
    if (self = [super init]) {
        self.delegate = self;
        self.dataSource = self;
        [self setupRefresh];
    }
    return self;
}

#pragma mark- 重写初始化
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    if (self = [super initWithFrame:frame style:style]) {
        self.delegate = self;
        self.dataSource = self;
        [self setupRefresh];
        _photoNum = 1;
        _qdfs = @"0";

    }
    return self;
}
#pragma mark- 数据请求

/**
 *  数据加载
 *
 *  @param reload 是否重置数据
 */
- (void)isReloadData:(BOOL)reload{
    
    NSInteger pageIndex = 1;
    
    if (reload) {
        
    } else {
        
        pageIndex = [self sc_currentPageNumWithTotalCount:self.orders.count];
    }
    
    NSMutableDictionary *parms = [[NSMutableDictionary alloc]init];
    [parms setObject:@"815bffb68e2ea44e38cf16a98a5a29a4" forKey:@"oauth_token"];
    [parms setObject:@"8e84bc64f03d73b5c75406ef1d7349f7" forKey:@"oauth_token_secret"];
    [parms setObject:@10 forKey:@"num"];
    [parms setObject:[NSString stringWithFormat:@"%ld",(long)pageIndex] forKey:@"page"];
    if(_headerView.searchBar.text.length>0){
        [parms setObject:@"2" forKey:@"history"];
    }else{
        [parms setObject:@"0" forKey:@"history"];
    }
    [parms setObject:_headerView.searchBar.text forKey:@"search"];
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_mySign params:parms];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        
        NSDictionary *dic = resp.originalDictionary;
        
        NSArray *array = dic[@"data"];

        
        if (reload) {
            [self.orders removeAllObjects];
        }
        for (NSDictionary *dic in array) {
            
            SignModel *model = [SignModel modelWithDic:dic];
            
            [self.orders addObject:model];
        }
        
        [self reloadData];
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
        [self.mj_header endRefreshing];
        [self.mj_footer endRefreshing];
    }];
    
}
/**
 *  在没有内容的情况下获取内容
 */
- (void)loadDataOfNone{
    if (self.orders.count == 0) {
        
        [self isReloadData:YES];
    }
}

/**
 *  重置内部数据
 */
- (void)reset{
    
    [self.orders removeAllObjects];
    
    [self reloadData];
}
/**
 *  刷新加载
 */
- (void)setupRefresh{
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self.mj_header beginRefreshing];
        
        [self isReloadData:YES];
        
    }];
    header.stateLabel.textColor = COLOR_TITLE_999999;
    header.lastUpdatedTimeLabel.textColor = COLOR_TITLE_999999;
    self.mj_header = header;
    
    
    MJRefreshAutoNormalFooter * foot = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self.mj_footer beginRefreshing];
        
        [self isReloadData:NO];
    }];
    foot.stateLabel.textColor = COLOR_TITLE_999999;
    self.mj_footer = foot;
    
}
/**
 根据ktid请求签到信息
 */
-(void)loadSignDataWith:(NSString*)ktid{
    
    NSMutableDictionary *para = [[NSMutableDictionary alloc]init];
    [para setObject:_ktid forKey:@"ktid"];
    [para setObject:OauthToken forKey:@"oauth_token"];
    [para setObject:OauthTokenSecret forKey:@"oauth_token_secret"];
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_SignDetail params:para];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        [self scanPopView:resp.dictionary];
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];
}

/**
 弹出签到页面
 */
-(void)scanPopView:(NSDictionary*)info{
    self.qdfs = @"1";
    self.isData = @"0";
    if (!_dismissBtn) {
        _dismissBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, SIZEHEIGHT)];
        _dismissBtn.backgroundColor = [UIColor blackColor];
        _dismissBtn.alpha = 0.65;
        [_dismissBtn addTarget:self action:@selector(popViewDismiss) forControlEvents:UIControlEventTouchUpInside];
        [[[UIApplication sharedApplication]keyWindow]  addSubview:_dismissBtn];
    }
    _dismissBtn.enabled = YES;
    _dismissBtn.hidden = NO;
    if ([info[@"ktxc"] isEqualToString:@"0"]) {// 课堂现场（需要照片为1，不需要为0）
        _popV = [[TodaySignView alloc]initWithFrame:CGRectMake(10, (SIZEHEIGHT-365)/2+20, SIZEWIDTH-20 , 365-60+ScaleSize(30))];
        
        [_popV resetView];
        
        
        _isImg = NO;//不需要照片的表示
    }else{
        _popV = [[TodaySignView alloc]initWithFrame:CGRectMake(10, (SIZEHEIGHT-365)/2+20, SIZEWIDTH-20 , 365+ScaleSize(30))];
        _popV.picImgBtn.userInteractionEnabled = YES;
        _isImg = YES;
    }
    _popV.bjTF.text = info[@"bj"];
    _popV.xsxhTF.text = info[@"xh"];
    _popV.xsxmTF.text = info[@"xsxm"];
    _popV.lsmcLabel.text = info[@"lsmc"];
    _popV.skrqLabel.text = info[@"skrq"];
    _popV.kcmcLabel.text = info[@"kcmc"];
    _popV.backgroundColor = [UIColor whiteColor];
    _popV.signDelegate = self;
    [[[UIApplication sharedApplication]keyWindow] addSubview:_popV];

}
#pragma mark  普通签到弹出页
-(void)initPopView:(SignModel*)model{
    _qdfs = @"0";
    _isData  = @"0";
    if (!_dismissBtn) {
        _dismissBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, SIZEHEIGHT)];
        _dismissBtn.backgroundColor = [UIColor blackColor];
        _dismissBtn.alpha = 0.65;
        [_dismissBtn addTarget:self action:@selector(popViewDismiss) forControlEvents:UIControlEventTouchUpInside];
        [[[UIApplication sharedApplication]keyWindow]addSubview:_dismissBtn];
    }
    _dismissBtn.enabled = YES;
    _dismissBtn.hidden = NO;
    _currentModel =  model;
    NSLog(@"%@",_currentModel);
    
    _ktid = _currentModel.ktid;
#warning 普通签到在此判断是否拍照
    if ([_currentModel.qdms isEqualToString:@"0"]) {// 课堂现场（需要照片为1，不需要为0）
        _popV = [[TodaySignView alloc]initWithFrame:CGRectMake(10, (SIZEHEIGHT-365)/2+20, SIZEWIDTH-20 , 365-60+ScaleSize(30))];
        
        [_popV resetView];
        
        
        _isImg = NO;
    }else{
        _popV = [[TodaySignView alloc]initWithFrame:CGRectMake(10, (SIZEHEIGHT-365)/2+20, SIZEWIDTH-20 , 365+ScaleSize(30))];
        _popV.picImgBtn.userInteractionEnabled = YES;
        _isImg = YES;
    }
    _popV.lsmcLabel.text = _currentModel.lsmc;
    _popV.kcmcLabel.text = _currentModel.kcmc;
    _popV.skrqLabel.text = _currentModel.sksj;
    
    _popV.backgroundColor = [UIColor whiteColor];
    _popV.signDelegate = self;
    [[[UIApplication sharedApplication]keyWindow] addSubview:_popV];
    
}

#pragma mark- 弹出页的签到按钮代理方法
-(void)clickSignBtn{
    if (_isImg) {
        
        
        [self upUserHeaderImageData];
        
        
        
    }else{
        
        [self loadSign:@"0"];
    }
}
- (void)loadSign:(NSString*)qdfs{
    
    if (_popV.xsxmTF.text.length == 0 || [_popV.xsxmTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"姓名不能为空" imageView:FailImage inView:[[UIApplication sharedApplication]keyWindow]];
        return;
    }
    if (_popV.xsxhTF.text.length == 0 || [_popV.xsxhTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"学号不能为空" imageView:FailImage inView:[[UIApplication sharedApplication]keyWindow]];
        return;
    }
    if (_popV.bjTF.text.length == 0 || [_popV.bjTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"班级不能为空" imageView:FailImage inView:[[UIApplication sharedApplication]keyWindow]];
        return;
        
    }
    

    
    //    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[self userDefaults:@"xtdz"],@"/index.php/apiv2/Sign/sign"];
//    NSString * urlString = [NSString stringWithFormat:@"%@%@%@", [self userDefaults:@"xtdz"], @"/index.php?s=apiv2/Sign/sign/", partsWithAPI];
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
//    NSString *  oauth_token = [NSString stringWithFormat:@"%@",[self userDefaults:@"oauth_token"]];
//    NSString *  oauth_token_secret = [NSString stringWithFormat:@"%@",[self userDefaults:@"oauth_token_secret"]];
    
    [para setObject:OauthToken forKey:@"oauth_token"];
    [para setObject:OauthTokenSecret forKey:@"oauth_token_secret"];
    NSLog(@"%@",_ktid);
    [para setObject:_ktid forKey:@"ktid"];
    [para setObject:_popV.xsxmTF.text forKey:@"xsxm"];
    [para setObject:_popV.xsxhTF.text forKey:@"xsxh"];
    [para setObject:_popV.bjTF.text forKey:@"xsbj"];
    
    NSString * UUID                  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];// 唯一标识码
    [para setValue:UUID forKey:@"sbbsm"];
    [para setObject:_qdfs forKey:@"qdfs"];
    //
    //    if (![_detailM.ktxc isEqualToString:@"1"]) {// 课堂现场（需要照片为1，不需要为0）
    //        _popV.picBtn.hidden = YES;
    //       }
    
    //    [para setObject:_pubImageData forKey:@"userpic"];
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_SignSign params:para];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        [self loadSignFinish:resp.originalDictionary];
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];
}

-(void)loadSignFinish:(NSDictionary*)operation{
    NSDictionary * cacheDic = [NSDictionary dictionaryWithDictionary:operation];
    NSLog(@"%@",cacheDic);
    if ([[cacheDic objectForKey:@"status"] intValue] == 0) {
        NSLog(@"签到成功");
        
        [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:SucceedImage inView:_popV];
        
        
        [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(popViewDismiss) userInfo:nil repeats:NO];
        
        
    }else{
        [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:FailImage inView:_popV];
        
    }
    
    
}


-(void)uploadPic{
    NSLog(@"点击上传图片");
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [self getPhotoWithSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"不支持拍照功能" imageView:nil inView:_popV];
    }

}
-(void)getPhotoWithSourceType:(UIImagePickerControllerSourceType)sourceType
{
    //访问系统的相机或者照片库
    //创建UIImagePickerController实例，用于访问系统照片库或者相机
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //根据不同的type加载不同的资源
    picker.sourceType = sourceType;
    picker.delegate = self;
    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    //允许对选中的资源进行后续操作
    picker.allowsEditing = YES;
    //调用系统资源控制器，一般通过模态化方式弹出
    [self.mainController presentViewController:picker animated:YES completion:^{
        _dismissBtn.hidden = YES;
        _popV.hidden = YES;
    }];
}
-(void)upUserHeaderImageData
{
    if (_popV.xsxmTF.text.length == 0 || [_popV.xsxmTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"姓名不能为空" imageView:FailImage inView:_popV];
        return;
    }
    if (_popV.xsxhTF.text.length == 0 || [_popV.xsxhTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"学号不能为空" imageView:FailImage inView:_popV];
        return;
    }
    if (_popV.bjTF.text.length == 0 || [_popV.bjTF.text isEqualToString: @" "]) {
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"班级不能为空" imageView:FailImage inView:_popV];
        return;
        
    }
    if(_photoNum!=2){
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"照片不能为空" imageView:FailImage inView:_popV];
        return;
    }
    

    
    NSMutableDictionary * para = [NSMutableDictionary dictionary];
    
//    NSString *  oauth_token = [NSString stringWithFormat:@"%@",[self userDefaults:@"oauth_token"]];
//    NSString *  oauth_token_secret = [NSString stringWithFormat:@"%@",[self userDefaults:@"oauth_token_secret"]];
    
    [para setObject:OauthToken forKey:@"oauth_token"];
    [para setObject:OauthTokenSecret forKey:@"oauth_token_secret"];
    
    [para setObject:_ktid forKey:@"ktid"];
    [para setObject:_popV.xsxmTF.text forKey:@"xsxm"];
    [para setObject:_popV.xsxhTF.text forKey:@"xsxh"];
    [para setObject:_popV.bjTF.text forKey:@"xsbj"];
    
    NSString * UUID                  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];// 唯一标识码
    [para setObject:UUID forKey:@"sbbsm"];
    [para setObject:_qdfs forKey:@"qdfs"];
    
    //    if (![_detailM.ktxc isEqualToString:@"1"]) {// 课堂现场（需要照片为1，不需要为0）
    //        _popV.picBtn.hidden = YES;
    //    }
    if (![_isData isEqualToString:@"0"]) {
        [para setObject:_pubImageData forKey:@"userpic"];
    }else{
        [[JLActionManager sharedInstance] showHUDWithLabelText:@"照片不能为空" imageView:FailImage inView:_popV];
        return;
    }
    NSString * urlString = [NSString stringWithFormat:@"%@%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"xtdz"]
, @"/index.php?s=apiv2/Sign/sign/"];

    [_headerManager POST:urlString parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData>formData) {
        
        [formData appendPartWithFileData:_pubImageData name:@"userpic" fileName:@"pic.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"operation == %@   responseObject == %@", operation, responseObject);
        
        [self responseUploadFinished:operation];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"1111Error: %@", error);
        //        _aler.message = @"网络故障，请重试";
        //        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(alertViewdismiss) userInfo:nil repeats:NO];
        //        [_aler show];
        // //POST_FAIL(@"网络连接失败");
    }];
}
-(void)responseUploadFinished:(AFHTTPRequestOperation *)operation
{
    //_touxiang1.image = [UIImage imageWithContentsOfFile:@"zhuzhenzhen.jpg"];
    NSData * data = [operation responseData];
    id cacheDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"头像 = %@",cacheDic);
    
    NSString * status =[NSString stringWithFormat:@"%@",[cacheDic objectForKey:@"status"]];
    if (![status isEqualToString:@"0"]) {
        [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:FailImage inView:_popV];
        
    }else{
        
        [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:SucceedImage inView:_popV];
        [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(popViewDismiss) userInfo:nil repeats:NO];
        
        
    }
}
#pragma mark- Tableview Delegate&Datasource

-(NSInteger)numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.orders.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TodaySignCell *cell = [TodaySignCell cellWithTableview:tableView];
    tableView.backgroundColor = BGC;
    [cell setTodayModel:self.orders[indexPath.row]];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    return self.headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return ScaleSize(156);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 145;
}

#pragma mark- 实现头视图代理方法
/**
 点击搜索
 */
-(void)searchTodaySignClick{
    [self isReloadData:YES];
}

/**
 点击扫描二维码
 */
-(void)codeButtonClick{
    

    if ([self.todayDelegate respondsToSelector:@selector(signWithCode)]) {
        [self.todayDelegate signWithCode];
    }
    
}

#pragma mark- 实现签到按钮点击方法
/**
 点击按钮签到
 */
-(void)clickCellSignBtn:(SignModel *)cellModel{
    [self initPopView:cellModel];
}
#pragma mark- 二维码代理方法实现
- (void)setKtidBack:(NSString *)ktid{
    _ktid = ktid;
    [self loadSignDataWith:_ktid];
}



#pragma mark - 弹出框消失
-(void)popViewDismiss{
    [_popV removeFromSuperview];
    _dismissBtn.enabled = NO;
    _dismissBtn.hidden = YES;
    
//    _pageT =1;
//    [self loadMySignData:@"0" andPage:1];
    [self isReloadData:YES];
    
    _isData = @"0";
}







#pragma mark- 懒加载控件
-(UIView *)headerView{
    if (!_headerView) {
        _headerView = [[SignTopView alloc]initWithStyle:SignTopStyleSerarchAndCode];
        _headerView.delegate = self;
    }
    return _headerView;
}
- (NSMutableArray<SignModel*>*)orders{
    
    if (!_orders) {
        _orders = [[NSMutableArray alloc]init];
    }
    return _orders;
}


@end
